package com.linkage.jz.bankruptcy.base;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.activity.user.ImageShowActivity;
import com.linkage.seapeak.pojo.UploadImage;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

public abstract class BaseCreateActivity extends BaseActivity {
    private final static String TAG = "BaseCreateActivity";

//    private final int MAX_IMG_SIZE = 27; // 最多上传27张
//    private final int MAX_IMG_ONCE = 9; // 单次最多9张


    public static final String NAME_ADD = "FILENAME_ADD.png";
    public static final int TYPE_EDIT = 1;
    public static final int TYPE_PREVIEW = 2;

    public static int mType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 选择图片、压缩图片
     *
     * @param mImgList
     */
    protected void pickAndUploadPic(final List<UploadImage> mImgList, final GridImagesAdapter adapter) {
//        LogUtil.v(TAG, "当前已上传图片张数：" + mImgList.size());
//        LogUtil.v(TAG, "剩余可上传张数：" + (adapter.maxSize - mImgList.size()));
//        int num = Math.min(adapter.maxSize - mImgList.size(), adapter.maxOnce);
//        LogUtil.v(TAG, "本次可选择张数：" + num);
        int listRealSize = mImgList.size();
//        if (mType == TYPE_EDIT) {
        listRealSize = listRealSize - 1;
//        }

        LogUtil.v(TAG, "当前已上传图片张数：" + listRealSize);
        LogUtil.v(TAG, "剩余可上传张数：" + (adapter.maxSize - listRealSize));
        int num = Math.min(adapter.maxSize - listRealSize, adapter.maxOnce);
        LogUtil.v(TAG, "本次可选择张数：" + num);

        RxGalleryFinal
                .with(this)
                .image()
                .radio()
                .gif(false)
                .multiple()
                .maxSize(num)
                .imageLoader(ImageLoaderType.UNIVERSAL)
                .subscribe(new RxBusResultDisposable<ImageMultipleResultEvent>() {
                    @Override
                    protected void onEvent(ImageMultipleResultEvent imageMultipleResultEvent) {
                        List<MediaBean> imgs = imageMultipleResultEvent.getResult();
                        List<String> imgpaths = new ArrayList<>();
                        for (int i = 0; i < imgs.size(); i++) {
                            imgpaths.add(imgs.get(i).getThumbnailBigPath());
                        }

                        uploadPics(imgpaths, mImgList, adapter);
                    }
                })
                .openGallery();
    }

    public static void sorFiles(List<UploadImage> fileList, boolean imgFirst) {
        // 排序，图片在下
        Collections.sort(fileList, (o1, o2) -> {
            if (FileUtil.isImage(o1.getFilename()) && !FileUtil.isImage(o2.getFilename())) {
                return imgFirst ? -1 : 1;
            } else if (!FileUtil.isImage(o1.getFilename()) && FileUtil.isImage(o2.getFilename())) {
                return imgFirst ? 1 : -1;
            } else if (FileUtil.isImage(o1.getFilename()) && FileUtil.isImage(o2.getFilename())) {
                if (FileUtil.isImage(o1.getFilename()) && TextUtils.equals(o2.getFilename(), NAME_ADD)) {
                    return -1;
                } else if (TextUtils.equals(o1.getFilename(), NAME_ADD) && FileUtil.isImage(o2.getFilename())) {
                    return 1;
                }
            }
            return 0;
        });
    }

    void uploadPics(final List<String> imgs, final List<UploadImage> mImgList, final GridImagesAdapter adapter) {
        Observable
                .create((Observable.OnSubscribe<List<File>>) subscriber -> {
                    List<File> files = new ArrayList<>();
                    try {
                        files.addAll(Luban.with(BaseCreateActivity.this).load(imgs).ignoreBy(1000).get());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    subscriber.onNext(files);
                    subscriber.onCompleted();
                })
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(() -> {
                    mShapeLoadingDialog.setLoadingText("文件上传中(1/" + imgTotal + ")");
                    mShapeLoadingDialog.setCanceledOnTouchOutside(false);
                    mShapeLoadingDialog.show();
                })
                .observeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<File>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<File> files) {
                        imgTotal = files.size();
                        imgFiles = files;
                        sorFiles(mImgList, true);
                        uploadOnePic(mImgList, adapter);
                    }
                });
    }


    /**
     * 上传图片
     */
    private int imgTotal = 0;
    private List<File> imgFiles;

    private void uploadOnePic(final List<UploadImage> mImgList, final GridImagesAdapter adapter) {
        final File file = imgFiles.get(0);
        imgFiles.remove(0);

        int imgIndex = imgTotal - imgFiles.size();
        mShapeLoadingDialog.setLoadingText("文件上传中(" + imgIndex + "/" + imgTotal + ")");


        MultipartBody.Part imgBody = null;
        if (!TextUtils.isEmpty(file.getAbsolutePath())) {
            imgBody = MultipartBody.Part.createFormData("Filedata", file.getName(),
                    RequestBody.create(MediaType.parse("image/jpeg"), file));
        }

//        final boolean tmpflag = showTrueFlag;
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

        Network.getAPIService()
                .uploadFile(RequestBody.create(null, userToken), imgBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }

                        JsonObject data = json.getAsJsonObject("data");
                        String strUlr = data.get("url").getAsString();
                        String realUrl = data.get("realUrl").getAsString();
//                        if(!tmpflag)
//                        {
                       String realSourceUrl = data.get("realSourceUrl").getAsString();
//                        }
                        UploadImage upimg = new UploadImage();
//                                        upimg.setFilename(file.getName());
                        upimg.setFilename("pic.jpg");
                        upimg.setFilepath(strUlr);
                        upimg.setFilesize((int) file.length());


                        upimg.setLoadUrl(realUrl);
                        upimg.setRealSourceUrl(realSourceUrl);
                        mImgList.add(upimg);
                        sorFiles(mImgList, true);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        if (imgFiles.size() > 0) {
                            LogUtil.w(TAG, "继续上传！！！");
                            uploadOnePic(mImgList, adapter);
                        } else {
                            LogUtil.w(TAG, "上传完成！！！");
                            mShapeLoadingDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (imgFiles.size() > 0) {
                            LogUtil.w(TAG, "继续上传！！！");
                            uploadOnePic(mImgList, adapter);
                        } else {
                            LogUtil.w(TAG, "上传完成！！！");
                            mShapeLoadingDialog.dismiss();
                        }
                    }
                });
    }

    public void imageSizeChange(int size) {

    }

    public void imageSizeChange(int tag, int size) {

    }

    public static class GridImagesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private List<UploadImage> list = new ArrayList<>();
        private int mType; // 1-编辑，2-预览
        private WeakReference<BaseCreateActivity> mWeekRefContext;
        private boolean enable = true;
        private Activity mActivity;

        private int maxSize = 27;
        private int maxOnce = 9;
        private Boolean showTrueFlag = true;

        public GridImagesAdapter(BaseCreateActivity baseCreateActivityWeakReference, int type) {
            this.mWeekRefContext = new WeakReference<>(baseCreateActivityWeakReference);
            mType = type;
            mActivity = baseCreateActivityWeakReference;
        }

        public GridImagesAdapter(BaseCreateActivity baseCreateActivityWeakReference, int type,Boolean showFlag) {
            this.mWeekRefContext = new WeakReference<>(baseCreateActivityWeakReference);
            mType = type;
            mActivity = baseCreateActivityWeakReference;
            showTrueFlag = showFlag;
        }

        public GridLayoutManager createLayoutManager() {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 4, LinearLayoutManager.VERTICAL,
                    false);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int i) {
                    switch (getItemViewType(i)) {
                        case 1:
                            return 1;
                        case 0:
                        default:
                            return 4;
                    }
                }
            });
            return gridLayoutManager;
        }


        public void setSelectMax(int selectMax) {
            this.maxSize = selectMax;
        }


        public void setList(List<UploadImage> list) {
            this.list = list;
        }

        public void setEnable(boolean enable) {
            this.enable = enable;
        }

        public class ImgViewHolder extends RecyclerView.ViewHolder {

            ImageView mImg;
            LinearLayout ll_del;

            public ImgViewHolder(View view) {
                super(view);
                mImg = view.findViewById(R.id.fiv);
                ll_del = view.findViewById(R.id.ll_del);
            }
        }

        public class FileViewHolder extends RecyclerView.ViewHolder {

            TextView tv_file_name;
            LinearLayout ll_del;

            public FileViewHolder(View view) {
                super(view);
                tv_file_name = view.findViewById(R.id.tv_file_name);
                ll_del = view.findViewById(R.id.ll_del);
            }
        }

        public void setTag(int tag) {
            //this.tag = tag;
        }

        @Override
        public int getItemCount() {
            // 预览模式
            if (mType == TYPE_PREVIEW) {
                return list.size();
            }
            boolean flag = false;
            for (int i = 0; i < list.size(); i++) {
                if (TextUtils.equals(list.get(i).getFilename(), NAME_ADD)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                UploadImage addImg = new UploadImage();
                addImg.setFilename(NAME_ADD);
                list.add(addImg);
                sorFiles(list, true);
            }
            if (list.size() > maxSize) {
                for (UploadImage img : list) {
                    if (TextUtils.equals(img.getFilename(), NAME_ADD)) {
                        list.remove(img);
                        break;
                    }
                }
            }

            return list.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (position >= list.size()) {
                return 1;
            }

            if (FileUtil.isImage(list.get(position).getFilename())) {
                return 1;
            }
            return 0;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            Context context = mWeekRefContext.get();
            if (viewType == 1) {
                ImgViewHolder viewHolder = new ImgViewHolder(View.inflate(context, R.layout.item_filter_image, null));
                if (mType == TYPE_PREVIEW) {
                    viewHolder.ll_del.setVisibility(View.GONE);
                } else {
                    viewHolder.ll_del.setVisibility(View.VISIBLE);
                }
                return viewHolder;
            } else {
                FileViewHolder viewHolder = new FileViewHolder(View.inflate(context, R.layout.item_filter_file, null));
                if (mType == TYPE_PREVIEW) {
                    viewHolder.ll_del.setVisibility(View.GONE);
                } else {
                    viewHolder.ll_del.setVisibility(View.VISIBLE);
                }
                return viewHolder;
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if (TextUtils.equals(list.get(position).getFilename(), NAME_ADD)) {
                ImgViewHolder viewHolder = (ImgViewHolder) holder;

                viewHolder.ll_del.setVisibility(View.GONE);
                viewHolder.mImg.setImageResource(R.drawable.ic_img_add);
                viewHolder.mImg.setScaleType(ImageView.ScaleType.FIT_XY);
                viewHolder.mImg.setOnClickListener(view -> {
                    if (!enable) {
                        return;
                    }
                    BaseCreateActivity baseCreateActivity = mWeekRefContext.get();
                    if (baseCreateActivity != null)
                        baseCreateActivity.pickAndUploadPic(list, GridImagesAdapter.this);
                });
                return;
            }


            if (holder instanceof ImgViewHolder) {
                ImgViewHolder viewHolder = (ImgViewHolder) holder;
                if (mType == TYPE_PREVIEW) {
                    viewHolder.ll_del.setVisibility(View.GONE);
                } else {
                    viewHolder.ll_del.setVisibility(View.VISIBLE);
                }
                String url = list.get(position).getLoadUrl();

                if(!showTrueFlag)
                {
                    String realSourceUrl =   list.get(position).getRealSourceUrl();
                    if(realSourceUrl!=null && !"".equalsIgnoreCase(realSourceUrl))
                    {
                        url = realSourceUrl;
                    }
                }
                viewHolder.ll_del.setOnClickListener(view -> {
                    int index = viewHolder.getAdapterPosition();
                    if (index != RecyclerView.NO_POSITION) {
                        list.remove(index);
                        notifyItemRemoved(index);
                        notifyItemRangeChanged(index, list.size());
                    }
                });

                viewHolder.mImg.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(mWeekRefContext.get())
                        .load(url)
                        .placeholder(R.mipmap.ic_launcher)
                        .into(viewHolder.mImg);

                viewHolder.mImg.setOnClickListener(v -> {

                    ArrayList listtmp = (ArrayList) list;
                    int adapterPosition = viewHolder.getAdapterPosition();
                    if(!showTrueFlag)
                    {
                        String realSourceUrl =   list.get(position).getRealSourceUrl();
                        if(realSourceUrl!=null && !"".equalsIgnoreCase(realSourceUrl))
                        {
                            ((UploadImage) listtmp.get(position)).setLoadUrl(((UploadImage) listtmp.get(position)).getRealSourceUrl());
                        }
                    }
                    ImageShowActivity.start(mWeekRefContext.get(), (ArrayList) list, adapterPosition,
                            mType == TYPE_EDIT ? ImageShowActivity.FROM_MUlTI_EDIT :
                                    ImageShowActivity.FROM_MUlTI_SHOW);
                });
            } else {
                FileViewHolder viewHolder = (FileViewHolder) holder;
                if (mType == TYPE_PREVIEW) {
                    viewHolder.ll_del.setVisibility(View.GONE);
                } else {
                    viewHolder.ll_del.setVisibility(View.VISIBLE);
                }
                viewHolder.tv_file_name.setText(list.get(position).getFilename());
                viewHolder.ll_del.setOnClickListener(view -> {
                    int index = viewHolder.getAdapterPosition();
                    if (index != RecyclerView.NO_POSITION) {
                        list.remove(index);
                        notifyItemRemoved(index);
                        notifyItemRangeChanged(index, list.size());
                    }
                });
            }
        }
    }
}
